package com.zkh.myframe.database.mapper.tag;

import java.util.ArrayList;
import java.util.List;

import com.zkh.myframe.database.mapper.parser.ForeachParser;
import com.zkh.myframe.database.mapper.parser.IfParser;
import com.zkh.myframe.database.mapper.parser.IncludeParser;
import com.zkh.myframe.database.mapper.parser.TrimParser;
import com.zkh.myframe.database.mapper.parser.WhereParser;
import com.zkh.myutils.markup.Element;

/**
 * 标签父类
 * @author zkh
 */
public class Tag {
	/** 存储标签（include | trim | where | foreach | if）数据  **/
	//include标签
	public List<Include> includes = new ArrayList<>();
	//foreach标签
	public List<Foreach> foreachs = new ArrayList<>();
	//where标签
	public List<Where> wheres = new ArrayList<>();
	//if标签
	public List<If> ifs = new ArrayList<>();
	//trim标签
	public List<Trim> trims = new ArrayList<>();
	
	//原始SQL
	protected StringBuffer originSQL = new StringBuffer();
	
	/**
	 * 解析标签
	 * @param tag 标签类
	 * @param pnode 父节点
	 * @param namespace 命名空间
	 */
	public void parseTag(Tag tag, Element pnode, String namespace) {
		//属性赋值
		renderAttribute(pnode);
		//没有子节点
		if(!pnode.hasChild()) {
			tag.appendSQL(pnode.getText(true).replaceAll("\\s+", " ").trim());
		}else {
			//遍历子节点
			pnode.getChildren().forEach(cnode->{
				//标签名称
				String tagName = cnode.getName();
				//判断标签（include，trim，where，foreach，if或文本）
				if(cnode.isText()) {
					tag.appendSQL(cnode.getText(true).replaceAll("\\s+", " ").trim());
				}else if("include".equalsIgnoreCase(tagName)){
					tag.appendInclude(IncludeParser.parse(cnode, namespace));
					tag.appendSQL("{:include}");
				}else if("where".equalsIgnoreCase(tagName)) {
					tag.appendWhere(WhereParser.parse(cnode, namespace));
					tag.appendSQL("{:where}");
				}else if("foreach".equalsIgnoreCase(tagName)) {
					tag.appendForeach(ForeachParser.parse(cnode, namespace));
					tag.appendSQL("{:foreach}");
				}else if("if".equalsIgnoreCase(tagName)) {
					tag.appendIF(IfParser.parse(cnode, namespace));
					tag.appendSQL("{:if}");
				}else if("trim".equalsIgnoreCase(tagName)) {
					tag.appendTrim(TrimParser.parse(cnode, namespace));
					tag.appendSQL("{:trim}");
				}
			});
		}
	}
	
	/**
	 * 渲染属性，由子类自己实现
	 */
	public void renderAttribute(Element attrs) {}

	/**
	 * 追加SQL
	 */
	public void appendSQL(String sql) {
		originSQL.append(' ').append(sql);
	}
	
	/**
	 * 追加Include
	 */
	public void appendInclude(Include include) {
		includes.add(include);
	}
	
	/**
	 * 追加Foreach
	 */
	public void appendForeach(Foreach foreach) {
		foreachs.add(foreach);
	}
	
	/**
	 * 追加Where
	 */
	public void appendWhere(Where where) {
		wheres.add(where);
	}
	
	/**
	 * 追加If
	 */
	public void appendIF(If If) {
		ifs.add(If);
	}
	
	/**
	 * 追加Trim
	 */
	public void appendTrim(Trim trim) {
		trims.add(trim);
	}

	/**
	 * 获取原SQL
	 */
	public StringBuffer getOriginSQL() {
		return originSQL;
	}

}
